<template>
    <el-form ref="videoForm" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm" status-icon>

        <el-form-item label="标题" prop="video_title" style="width: 70%;">
            <el-input v-model="ruleForm.video_title" />
        </el-form-item>

        <el-form-item label="作者" prop="video_author" style="width: 70%;">
            <el-input v-model="ruleForm.video_author" />
        </el-form-item>

        <el-form-item label="分类" style="width: 70%;">
            <el-select v-model="ruleForm.video_navigate" placeholder="请选择">
                <el-option v-for="item in navs.result" :key="item.nav_id" :label="item.nav_text" :value="item.nav_text" />
            </el-select>
        </el-form-item>

        <el-form-item style="width: 70%;">
            <div class="file-box">
                <input type="file" class="my-file" ref="video_file">
                <p class="my-file-msg">选择视频文件</p>
            </div>
        </el-form-item>

        <el-form-item label="时间" required>
            <el-col :span="11">
                <el-form-item prop="video_create_time">
                    <el-date-picker v-model="ruleForm.video_create_time" type="date" label="" placeholder="开始"
                        style="width: 100%" disabled />
                </el-form-item>
            </el-col>
            <el-col class="text-center" :span="2">
                <span class="text-gray-500"></span>
            </el-col>
        </el-form-item>

        <el-form-item label="内容介绍" style="width: 70%;">
            <WangEditor @handleBlurxxxx="addWangEditorVideo" :contentxxx="video"></WangEditor>
        </el-form-item>

        <el-form-item style="width: 70%;">
            <!-- 上传视频封面 -->
            <el-upload class="upload-demo" drag :on-change="handleImgChange" accept="image/*" :auto-upload="false"
                style="width:100%">
                <template v-if="!ruleForm.video_pic">
                    <el-icon class="el-icon--upload">
                    <upload-filled />
                </el-icon>
                <div class="el-upload__text" >
                    <div>拖拽到此处</div>
                    <div>或点击上传</div>
                </div>
                </template>
                <template #tip>
                    <div class="el-upload__tip">
                        <div style="position:relative;" v-if="ruleForm.video_pic">
                            <span style="cursor: pointer; padding:5px 0; width:100%; padding-left: 20px; position: absolute; bottom: 0px; left:0px; font-size: 14px; background-color: rgba(255, 255, 255, .45);" @click="rmVideoPic">删除</span>
                            <img v-if="ruleForm.video_pic" :src="ruleForm.video_pic" alt="" style="height: 120px;">
                        </div>
                    </div>
                </template>
            </el-upload>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="addVideo(videoForm)">发布内容</el-button>
            <el-button @click="resetForm(videoForm)">重置</el-button>
        </el-form-item>

    </el-form>
</template>
<script lang="ts" setup>
// 导入富文本框组件
import WangEditor from '../../components/WangEditor.vue'
// 引入处理html字符串的插件
import { escape, unescape } from 'html-escaper'
// 导入格式化时间插件
import moment from "moment";
// 导入消息提示框
import { ElMessage } from 'element-plus';
// 导入定义数据的方法
import { ref, reactive, onMounted } from 'vue';
// 导入表单组件对象
import type { FormInstance, FormRules } from 'element-plus';
// 导入相关接口
import { videoAddVideoPicApi, videoDetailApi, navListApi, videoUpdateApi , videoRomovePicApi} from '../../http/request';
// 导入创建路由方法
import { useRouter } from 'vue-router';
// 处理视频上传
import { SliceUpload } from './js/SliceUpload'
const video_file = ref("video_file");
// console.log(video_file)
// const api_video_pic: any = ref('http://localhost:3002/video/add_video_pic');
// 定义路由
const $router = useRouter();
// 定义变量
let video_id: any = ref("");
// 获取token
let token: any = localStorage.getItem('token');
// 定义内容表单实例
const videoForm = ref<FormInstance>();
// 定义对象记录表单提交的数据
const ruleForm = reactive({
    video_title: '', // 内容标题
    video_author: '', // 内容作者
    video_create_time: '',// 内容创建时间
    video_text: '',// 内容介绍
    video_navigate: '分类', //分类
    video_pic: ''// 内容封面
})
// 设置表单约束
const rules = reactive<FormRules>({
    // 标题
    video_title: [
        { required: true, message: '请输入内容名称', trigger: 'blur' }
    ],
    // 作者
    video_author: [
        {
            required: true,
            message: '请输入作者',
            trigger: 'change',
        },
    ],
    // 创建时间
    video_create_time: [
        {
            type: 'date',
            required: true,
            message: '请选择一个时间',
            trigger: 'change',
        },
    ],
    // 描述文字
    video_text: [
        { required: true, message: '请输入内容解析', trigger: 'blur' },
    ],
})
// 设置时间（默认）
ruleForm.video_create_time = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
// 获取富文本框的内容
// 编写添加内容方法
// escape('<p>')
// unescape('&lt;p&gt;p&lt;p&gt;')
const addWangEditorVideo = (result: any) => {
    // console.log("富文本框的内容:", result)
    // 记录富文本输入框（整合html的标点符号）
    // console.log(escape(result.content))
    ruleForm.video_text = escape(result.content);
}
// 定义变量传值给富文本框
let video = ref("")

const addVideo = async (formObj: FormInstance | undefined) => {
    if (!formObj) return
    await formObj.validate(async (valid, fields) => {
        if (valid) {
            let { video_title, video_author, video_text, video_pic, video_navigate } = ruleForm;
            let elementInput: any = video_file.value;
            // 检查视频文件信息
            // console.log(elementInput.files);
            // 调用该函数用于实现数据提交（视频，标题，作者，描述，导航）
            SliceUpload(elementInput, video_title, video_author, video_text, video_navigate, video_pic)
                .then(
                    () => {
                        // 重置表单
                        formObj.resetFields();
                        // 延迟300ms跳转页面
                        let timeout = setTimeout(() => {
                            $router.push({ path: '/video/list?123123' });
                            clearTimeout(timeout);
                        }, 300)
                        // 提示
                        ElMessage({
                            message: '完成资料上传',
                            type: 'success',
                        });
                        // console.log('完成资料上传')
                    }
                )
          
        } else {
            console.log('error submit!', fields)
            // 提示
            ElMessage({
                message: 'error submit!',
                type: 'warning',
            });
        }
    })
}
// 编写重置内容方法
const resetForm = (formObj: FormInstance | undefined) => {
    if (!formObj) return
    formObj.resetFields()
}
// 获取内容详情
const DetailVideo = (video_id: any) => {
    // 获取内容详情
    videoDetailApi({ token, video_id: video_id.value})
        .then(
            (data: any) => {
                console.log(data)
                if (data.code == 200) {
                    let { video_title, video_author, video_create_time, video_navigate, video_text,video_pic } = data.result[0];
                    ruleForm.video_title = video_title;
                    ruleForm.video_author = video_author;
                    ruleForm.video_create_time = video_create_time;
                    ruleForm.video_navigate = video_navigate;
                    ruleForm.video_text = unescape(video_text);
                    ruleForm.video_pic = unescape(video_pic);
                    video.value = unescape(video_text);
                }
            }
        )
        .catch(
            error => {
                console.log(error);
            }
        )
}
// 记录导航
let navs: any = reactive({ result: [] })
// 初始化导航列表
const initnavList = async () => {
    // 调用导航列表接口
    await navListApi()
        .then(
            (data: any) => {
                if (data.code == 200) {
                    // console.log(data);
                    let { result } = data;
                    navs.result = result;
                }
            }
        )
}

// 调用挂载钩子函数
onMounted(() => {
    // 初始化内容
    // console.log(video_id)
    if ($router && $router.currentRoute.value.query) {
        video_id.value = $router.currentRoute.value.query.video_id
        if (video_id.value) {
            DetailVideo(video_id)
        }
    }
    // 初始化 
    initnavList();
})
// 设置视频封面
const handleImgChange = async (event: any) => {
    let file = event['raw'];
    // console.log(file)
    if (file) {
        let formData = new FormData();
        formData.append('photo', file);
        await videoAddVideoPicApi(formData).then(
            res => {
                // console.log(res);
                let { video_pic } = res;
                ruleForm.video_pic = video_pic;
            }
        )
    } else {
        ElMessage("请选择图片。")
    }
}
// 选择视频文件
// const chooseVideo = () => {
//     let elementInput: any = video_file.value;
//     console.log(elementInput.files);
// }

// 删除视频封面
const rmVideoPic = ()=> {
    videoRomovePicApi({video_pic: ruleForm.video_pic})
    .then(
        res=>{
            // console.log('xx:',res)
            if(res.code ==200) {
                ruleForm.video_pic = "";
            }
        }
    )
}
</script>
<style lang="scss">
.el-upload-dragger {
    margin-bottom: 20px;
    padding-top: 0px;
    padding-bottom: 0px;

    div {
        padding: 0 !important;
        margin: 0 !important;
    }
}

.demo-ruleForm {
    ::v-deep .el-picker-panel__body {
        z-index: 100000000000;
        background-color: #ccc;
    }
}

.el-upload-dragger {
    margin-bottom: 20px;
    padding-top: 0px;
    padding-bottom: 0px;

    div {
        padding: 0 !important;
        margin: 0 !important;
    }
}

.demo-ruleForm {
    ::v-deep .el-picker-panel__body {
        z-index: 100000000000;
        background-color: #ccc;
    }
}

.file-box {
    position: relative;
}

.file-box .my-file {
    height: 40px;
    line-height: 40px;
    background-color: transparent;
    border: 0;

}
</style>